//
//  WLDashLine.swift
//  WLVom
//
//  Created by Xiaochao Su 苏小超 on 2018/1/15.
//  Copyright © 2018年 CocoaPods. All rights reserved.
//

import UIKit

class WLDashLine: UIView {

    var shapeLayer : CAShapeLayer?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupView()
    }
    
    private func setupView() {
        let view = viewFromNibForClass()
        view.frame = bounds
        
        // Auto-layout stuff.
        view.autoresizingMask = [
            UIView.AutoresizingMask.flexibleWidth,
            UIView.AutoresizingMask.flexibleHeight
        ]
        addSubview(view)
    }
    
    override func layoutSubviews() {
        //drawDashLine()
        drawDashLine()
    }
    
    func drawDashLine(){
        shapeLayer?.removeFromSuperlayer()
        shapeLayer = CAShapeLayer()
        
        shapeLayer?.bounds = self.bounds
        //        只要是CALayer这种类型,他的anchorPoint默认都是(0.5,0.5)
        shapeLayer?.anchorPoint = CGPoint(x: 0, y: 0)
        //        shapeLayer.fillColor = UIColor.blue.cgColor
        shapeLayer?.strokeColor = UIColor.blue.cgColor // Vom_Color_229.cgColor
        
        shapeLayer?.lineWidth = self.frame.size.height
        shapeLayer?.lineJoin = kCALineJoinRound
//        shapeLayer?.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer?.lineDashPattern = [NSNumber(value: 5),NSNumber(value: 5)]
        
        let path = CGMutablePath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: self.frame.size.width, y: 0))
        
        shapeLayer?.path = path
        if let l = shapeLayer{
            self.layer.addSublayer(l)
        }
        
    }
    
//    private func drawDashLine(){
//        UIGraphicsBeginImageContext(dashImageView.frame.size) // 位图上下文绘制区域
//        dashImageView.image?.draw(in: dashImageView.bounds)
//
//        let context:CGContext = UIGraphicsGetCurrentContext()!
//
//        context.setLineCap(CGLineCap.square)
//
//        let lengths:[CGFloat] = [5,5] // 绘制 跳过 无限循环
//
//        context.setStrokeColor(UIColor.init(red: 229, green: 229, blue: 229).cgColor)
//        context.setLineWidth(1.5)
//        context.setLineDash(phase: 0, lengths: lengths)
//        context.move(to: CGPoint(x: 0, y: 0))
//        context.addLine(to: CGPoint(x: Common.screenWidth, y: 0))
//        context.strokePath()
//
//        dashImageView.image = UIGraphicsGetImageFromCurrentImageContext()
//    }
    
    private func viewFromNibForClass() -> UIView {

        let nib = UINib(nibName: String(describing: type(of: self)), bundle: nil)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        return view
    }
}
